package com.cl.code.common.component.processor;

import com.cl.code.common.utils.GenericUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author chengliang
 * @since 1.0.0
 */
public abstract class GenericBeanPostProcessor<T> implements BeanPostProcessor {

    private final Class<?> targetType;

    public GenericBeanPostProcessor() {
        // 获取当前类的泛型类型
        targetType = GenericUtils.getGenericType(this.getClass(), 0);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (targetType != null && targetType.isInstance(bean.getClass())) {
            return postProcessBeforeInit((T) bean, beanName);
        }
        return bean;
    }

    public T postProcessBeforeInit(T bean, String beanName) {
        return bean;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (targetType != null && targetType.isInstance((T) bean)) {
            return postProcessAfterInit((T) bean, beanName);
        }
        return bean;
    }

    public T postProcessAfterInit(T bean, String beanName) {
        return bean;
    }
}
